<template>
  <div>
    <div
      class="-mt-46 h-[calc(100vh-0px)] custom-navbar-wrapper-f5f5f5 pt-46 px-15 flex flex-col"
    >
      <!-- 加载状态 -->
      <div v-if="loading" class="py-50 flex justify-center items-center">
        <van-loading size="24px" vertical>
          <span class="text-13 text-999 mt-10">加载订单详情中...</span>
        </van-loading>
      </div>
      <!-- 错误状态 -->
      <div v-if="error" class="py-50 text-center">
        <div class="mt-20 text-15 text-999">加载订单详情失败</div>
        <div class="mt-10 text-13 text-999">
          {{ errorMessage }}
        </div>
      </div>
      <!-- 订单详情内容 -->
      <div
        v-if="!loading && !error"
        class="mt-15 py-12 px-15 rounded-10 bg-white"
      >
        <!-- 渠道订单 -->
        <div v-if="receivedType === ORDER_TYPE_ENUM.CHANNELS">
          <div class="flex items-center justify-between mb-8 text-13">
            <div class="leading-18">该课程用于权益兑换</div>
            <div class="px-6 h-22 leading-22 rounded-4" :class="statusClass">
              {{ statusText }}
            </div>
          </div>
          <div class="flex pt-10 border-t-1 border-F5F5F5 border-solid">
            <van-image
              :src="channelDetail.channelProdCover"
              class="w-100 h-100"
              radius="10"
            />
            <div class="flex-1 w-0 ml-15">
              <div class="flex items-start justify-between text-15">
                <div class="break-all">
                  {{ channelDetail.channelProdName }}
                </div>
                <div class="font-bold ml-15">¥{{ channelDetail.price }}</div>
              </div>
              <div class="mt-6 text-13 text-999999 text-right">
                <div>x{{ channelDetail.quantity }}</div>
              </div>
            </div>
          </div>
          <div class="mt-10 py-10 border-b-1 border-solid border-F5F5F5">
            <div class="pt-12 pb-15 px-15 rounded-10 bg-F5F5F5">
              <div class="text-13">
                可<span class="text-with-underline">兑换权益</span
                >具体内容如下：
              </div>
              <div class="flex mt-12">
                <div class="relative w-100 h-100 rounded-10 overflow-hidden">
                  <van-image
                    :src="
                      channelDetail.rechargeProdCover ||
                      `${IMG_CDN_39}/member/ai_coin_cover.png`
                    "
                    class="w-100 h-100"
                    radius="10"
                  />
                  <div
                    class="absolute bottom-0 right-0 px-6 h-22 leading-22 text-13 text-white rounded-tl-10 c-translucent-balck50"
                  >
                    {{ COMBO_TYPE_MAP[channelDetail.comboType] }}
                  </div>
                </div>
                <div class="flex-1 w-0 ml-15">
                  <div class="text-15 break-all">
                    {{ channelDetail.rechargeProdName }}
                  </div>
                  <div class="mt-10 text-12 text-999999 leading-18">
                    体验包含{{ assetContentText }}
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>
        <!-- 平台订单 -->
        <div v-else>
          <div class="flex items-center justify-between mb-8 text-13">
            <div class="font-bold leading-18">
              【{{ COMBO_TYPE_MAP[platformDetail.comboType] }}】
            </div>
            <div class="px-6 h-22 leading-22 rounded-4" :class="statusClass">
              {{ statusText }}
            </div>
          </div>
          <div class="flex pt-10 border-t-1 border-F5F5F5 border-solid">
            <van-image
              :src="
                platformDetail.rechargeProdCover ||
                `${IMG_CDN_39}/member/ai_coin_cover.png`
              "
              class="w-100 h-100"
              radius="10"
            />
            <div class="flex-1 w-0 ml-15">
              <div class="flex items-start justify-between text-15">
                <div class="break-all">
                  {{ platformDetail.rechargeProdName }}
                </div>
                <div class="font-bold ml-15">
                  ¥{{ platformDetail.payMoney }}
                </div>
              </div>
              <div
                class="flex items-start justify-between mt-10 text-12 text-999999"
              >
                <div class="mr-55 leading-18">
                  体验包含{{ assetContentText }}
                </div>
                <div>x1</div>
              </div>
            </div>
          </div>
        </div>
        <!-- 详情 -->
        <div class="mt-24">
          <div class="flex items-center mb-15 text-13 leading-18">
            <div class="text-999999">实付款</div>
            <div class="ml-auto">
              <span class="text-FF4A35 font-bold">¥</span>
              <template
                v-if="payMoneySplit(currentDetails.payMoney).decimalPart"
              >
                <span class="text-20 text-FF4A35 font-bold">{{
                  payMoneySplit(currentDetails.payMoney).integerPart
                }}</span>
                <span class="text-FF4A35 font-bold"
                  >.{{
                    payMoneySplit(currentDetails.payMoney).decimalPart
                  }}</span
                >
              </template>
              <template v-else>
                <span class="text-20 text-FF4A35 font-bold">{{
                  payMoneySplit(currentDetails.payMoney).integerPart
                }}</span>
              </template>
            </div>
          </div>
          <div
            v-if="receivedType === ORDER_TYPE_ENUM.CHANNELS"
            class="flex items-center mb-15 text-13 leading-18"
          >
            <div class="text-999999">下单渠道</div>
            <div
              v-if="channelDetail.channelType === CHANNEL_ENUM.WX_VIDEO"
              class="ml-auto flex items-center"
            >
              <svg-icon name="icon-shipinhao" :size="16" color="#FA9D3B" />
              <span class="ml-4">视频号</span>
            </div>
          </div>
          <div class="flex items-center mb-15 text-13 leading-18">
            <div class="text-999999">订单编号</div>
            <div class="ml-auto line-clamp-1 break-words max-w-180">
              <span v-if="receivedType === ORDER_TYPE_ENUM.CHANNELS">{{
                channelDetail.recordNo
              }}</span>
              <span v-if="receivedType === ORDER_TYPE_ENUM.PLATFORM">{{
                platformDetail.orderNo
              }}</span>
            </div>
            <div class="px-7 text-CCCCCC">|</div>
            <div
              class="flex-shrink-0 text-4D00FF cursor-pointer"
              @click="
                copyOrderNumber(
                  receivedType === ORDER_TYPE_ENUM.CHANNELS
                    ? channelDetail.recordNo
                    : platformDetail.orderNo
                )
              "
            >
              复制
            </div>
          </div>
          <div class="flex items-center mb-15 text-13 leading-18">
            <div class="text-999999">下单时间</div>
            <div class="ml-auto">
              <span v-if="receivedType === ORDER_TYPE_ENUM.CHANNELS">{{
                channelDetail.orderTime
              }}</span>
              <span v-if="receivedType === ORDER_TYPE_ENUM.PLATFORM">{{
                platformDetail.createTime
              }}</span>
            </div>
          </div>
          <div class="flex items-center mb-15 text-13 leading-18">
            <div class="text-999999">支付时间</div>
            <div class="ml-auto">
              {{ currentDetails.payTime || "--" }}
            </div>
          </div>
          <div class="flex items-center mb-15 text-13 leading-18">
            <div class="text-999999">支付方式</div>
            <div class="ml-auto">
              {{ PAY_METHOD_MAP[currentDetails.paymentMethod] }}
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- 复制成功提示 -->
    <van-toast v-model:show="showCopySuccess" message="复制成功" />
  </div>
</template>

<script setup lang="ts">
import { onMounted, ref, computed } from "vue";
import { useRoute } from "vue-router";
import { useClipboard } from "@vueuse/core";
import { showToast } from "vant";
import {
  ChannelRechargeOrderDetailInfoData,
  RechargeOrderDetailInfoData,
  getChannelRechargeOrderDetail,
  getRechargeOrderDetail
} from "@/api/OrderDetails";
import { CHANNEL_ENUM, ORDER_TYPE_ENUM, PAY_STATUS_ENUM } from "@/enums";
import {
  ASSET_TYPE_MAP,
  COMBO_TYPE_MAP,
  IMG_CDN_39,
  PAY_METHOD_MAP,
  PAY_STATUS_MAP
} from "@/constants";
import { RechargeAssetInfoData } from "@/api/OrderList";

// 获取路由参数
const route = useRoute();
const receivedId = ref<string>("");
const receivedType = ref<string>("");

// 加载状态
const loading = ref(true);
const error = ref(false);
const errorMessage = ref("");

// 复制相关
const showCopySuccess = ref(false);
const { copy, isSupported } = useClipboard();

// 订单详情信息
const channelDetail = ref<ChannelRechargeOrderDetailInfoData>({
  channelProdCover: "",
  channelProdName: "",
  channelType: 0,
  comboType: 0,
  createTime: "",
  orderTime: "",
  payMoney: 0,
  payTime: "",
  paymentMethod: 0,
  price: 0,
  quantity: 0,
  rechargeAssetInfoVoList: [],
  rechargeProdCover: "",
  rechargeProdName: "",
  recordNo: "",
  status: 0
});

const platformDetail = ref<RechargeOrderDetailInfoData>({
  channelProdCover: "",
  channelProdName: "",
  channelType: 0,
  comboType: 0,
  createTime: "",
  orderNo: "",
  orderTime: "",
  payMoney: 0,
  payTime: "",
  paymentMethod: 0,
  price: 0,
  quantity: 0,
  rechargeAssetInfoVoList: [],
  rechargeProdCover: "",
  rechargeProdName: "",
  status: 0
});

// 金额分割
const payMoneySplit = (
  money: number
): {
  integerPart: string;
  decimalPart?: string;
} => {
  // 确保是数字类型
  if (typeof money !== "number") {
    return { integerPart: "0" };
  }

  // 格式化为两位小数
  const formatted = money.toFixed(2);
  const parts = formatted.split(".");

  return {
    integerPart: parts[0],
    decimalPart: parts[1]
  };
};

// 计算属性：获取当前详情
const currentDetails = computed(() => {
  return receivedType.value === ORDER_TYPE_ENUM.CHANNELS
    ? channelDetail.value
    : platformDetail.value;
});

// 计算属性：资产内容文本
const assetContentText = computed(() => {
  const assetList =
    receivedType.value === ORDER_TYPE_ENUM.CHANNELS
      ? channelDetail.value.rechargeAssetInfoVoList
      : platformDetail.value.rechargeAssetInfoVoList;

  return formatAssetContent(assetList);
});

// 计算属性：状态类名
const statusClass = computed(() => {
  const status =
    receivedType.value === ORDER_TYPE_ENUM.CHANNELS
      ? channelDetail.value.status
      : platformDetail.value.status;

  return status === PAY_STATUS_ENUM.REFUND
    ? "text-FF4A35 c-bg-FF4A35-10"
    : "text-4D00FF bg-E2E0FF";
});

// 计算属性：状态文本
const statusText = computed(() => {
  const status =
    receivedType.value === ORDER_TYPE_ENUM.CHANNELS
      ? channelDetail.value.status
      : platformDetail.value.status;

  return PAY_STATUS_MAP[status] || "--";
});

// 格式化资产内容
const formatAssetContent = (assetTypeList: RechargeAssetInfoData[]): string => {
  if (!assetTypeList || assetTypeList.length === 0) return "无权益信息";

  const assetContentArr = [];
  for (let item of assetTypeList) {
    if (ASSET_TYPE_MAP[item.assetType] && item.assetAmount > 0) {
      assetContentArr.push(
        `${ASSET_TYPE_MAP[item.assetType]}${item.assetAmount}个`
      );
    }
  }

  return assetContentArr.length > 0 ? assetContentArr.join("；") : "无具体权益";
};

// 复制订单号
const copyOrderNumber = (orderNumber: string) => {
  if (orderNumber) {
    if (isSupported) {
      copy(orderNumber);
      showCopySuccess.value = true;
    } else {
      showToast("您的浏览器不支持复制功能");
    }
  }
};

// 获取订单详情
const fetchOrderDetail = async () => {
  try {
    loading.value = true;
    error.value = false;

    if (receivedType.value === ORDER_TYPE_ENUM.CHANNELS) {
      channelDetail.value = await getChannelRechargeOrderDetail(
        receivedId.value
      );
    } else {
      platformDetail.value = await getRechargeOrderDetail(receivedId.value);
    }
  } catch (e: any) {
    console.error("获取订单详情失败:", e);
    error.value = true;
    errorMessage.value = e.message || "加载失败，请稍后再试";
  } finally {
    loading.value = false;
  }
};

onMounted(() => {
  // 从路由参数中获取id和类型
  receivedId.value = route.params.id as string;
  receivedType.value = route.params.orderType as string;

  if (!receivedId.value || !receivedType.value) {
    error.value = true;
    errorMessage.value = "缺少订单参数";
    loading.value = false;
    return;
  }

  fetchOrderDetail();
});
</script>

<style scoped lang="less">
</style>
